<?php
/**
 * Free Web File Manager is free software released under MIT License.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 * George Sarafov
 * http://freewebfilemanager.com
 */

/** WordPress Administration Bootstrap */

header('Content-Type: application/json');


require( dirname(__FILE__) . '/../wp-load.php' );
global $wpdb;





/// 封装对数据库的操作
class GSFileSystemFileStorage {

    public $wpdb;

    public function __construct($wpdb){
        $this->wpdb=$wpdb;
    }
    public function is_dir($file) {
        return @is_dir($file);
    }

    public function file_exists($file) {
        return @file_exists($file);
    }
    /*
     *
     *
     查看 该id的文件或文件夹是否存在
	*/
    public function file_exists_2($id) {
        return $this->wpdb->query("SELECT *  FROM wp_catalogs WHERE id ='".$id."' and isValid='0'")  ;
    }
    /*
         *
         *
         查看 该id的文件或文件夹是否存在 并获取结果
        */
    public function file_exists_1($id) {
        return $this->wpdb->get_results("SELECT *  FROM wp_catalogs WHERE id ='".$id."'  and isValid='0'")  ;
    }



    /*
     *
     *
     查看 该id的文件夹下  最新上传的文件
    */
    public function lastfile($id) {
        return $this->wpdb->get_results("SELECT *  FROM wp_catalogs WHERE parentId ='".$id."'  and isValid='0' and type='1' order by createTime desc")  ;
    }



    /*
     * ////查看当前目录下 该文件名的文件或文件夹是否存在
     */

    public function filename_exists($id,$filename) {

        return $this->wpdb->query("SELECT *  FROM wp_catalogs WHERE parentId ='".$id."' AND name='".$filename."'  and isValid='0'")  ;
    }

    public function scandir($id) {
        $querystr = "SELECT * FROM wp_catalogs WHERE parentId ='".$id."'  and isValid='0' and display='0'  ORDER BY listOrder "  ;
        return  $this->wpdb->get_results($querystr);

    }

    public function filesize($file) {
        return @filesize($file);
    }

    public function deleteFile($file){
        return @unlink($file);
    }

    public function deleteDirectory($dirname){
        $files = scandir($dirname);
        if (count($files) > 2) {
            foreach( $files as $file ) {
                if ($file == '.' || $file == '..') {
                    continue;
                }
                if (is_dir($dirname.'/'.$file)) {
                    $this->deleteDirectory($dirname.'/'.$file);
                } else {
                    @unlink($dirname.'/'.$file);
                }
            }
        }
        return rmdir($dirname);
    }


    /*
     *
     * 根据 id he  filename 新建文件夹
     *
     */
    public function makeDirectory($id,$dirname){
        $result=  $this->wpdb->get_results("SELECT pathName FROM wp_catalogs WHERE id ='".$id."'  and isValid='0' " );

        $result1=  $this->wpdb->get_results("SELECT listOrder FROM wp_catalogs order by listOrder desc limit 0,1 " );
        $num=$result1[0]->listOrder+1;
        return $this->wpdb->query("INSERT INTO `wp_catalogs` ( `type`, `parentId`, `name`, `netAddr`, `fileAddr`, `pdfAddr`, `createTime`, `isValid`, `listOrder`,`display`, `pathName`) VALUES ( '2', '".$id."', '".$dirname."', NULL, NULL, NULL,now(), '0', '".$num."', '0', '".$result[0]->pathName."/".$dirname."')");
    }


    /*
     *
     * 根据 id he  filename 新建网址链接
     *
     */
    public function newLink($id,$dirname,$addr){
        $result1=  $this->wpdb->get_results("SELECT listOrder FROM wp_catalogs order by listOrder desc limit 0,1 " );
        $num=$result1[0]->listOrder+1;
        return $this->wpdb->query("INSERT INTO `wp_catalogs` ( `type`, `parentId`, `name`, `netAddr`, `fileAddr`, `pdfAddr`, `createTime`, `isValid`, `listOrder`,`display`, `pathName`) VALUES ( '0', '".$id."', '".$dirname."', '".$addr."', NULL, NULL, now(), '0', '".$num."', '0', NULL)");
    }

    /*
     *
     * 根据 id he  filename 修改网址链接
     *
     */
    public function changeLink($id,$dirname,$addr){
        return $this->wpdb->query("update  `wp_catalogs` set name='".$dirname."' , netAddr='".$addr."' where id='".$id."' ");

    }

    /*
         *
         * 根据 id he  filename 新建天气路线
         *
         */
    public function newWeatherPath($id,$source,$dest){
        $result1=  $this->wpdb->get_results("SELECT listOrder FROM wp_catalogs order by listOrder desc limit 0,1 " );
        $num=$result1[0]->listOrder+1;
        return $this->wpdb->query("INSERT INTO `wp_catalogs` ( `type`, `parentId`, `name`, `source`, `fileAddr`, `pdfAddr`, `createTime`, `isValid`, `listOrder`,`display`, `dest`) VALUES ( '3', '".$id."', '".$source."--".$dest."', '".$source."', NULL, NULL,now(), '0',  '".$num."', '0', '".$dest."')");
    }

    /*
     *
     * 根据 id he  filename 修改天气路线
     *
     */
    public function changeWeatherPath($id,$source,$dest){

        return $this->wpdb->query("update  `wp_catalogs` set name='".$source."--".$dest."' , source='".$source."' , dest = '".$dest."' where id='".$id."' ");
    }





    /*
     *
     * $result=  $this->wpdb->get_results("SELECT pathName FROM wp_catalogs WHERE id ='".$id."'  " );
            return $this->wpdb->query("INSERT INTO `wp_catalogs` ( `type`, `parentId`, `name`, `netAddr`, `fileAddr`, `pdfAddr`, `createTime`, `isValid`, `listOrder`,`display`, `pathName`) VALUES ( '2', '"
                .$id."', '".$dirname."', NULL, NULL, NULL, '".$time."', '0', '0','0','".$result[0]->pathName."//".$dirname."')");
     */

    /*


    /*
     *
     * 根据 id    filename 修改文件夹名称
     *
     */
    public function renameItemName($id,$name){

        return $this->wpdb->query("update  `wp_catalogs` set name='".$name."'  where id='".$id."' ");
    }

    /*
     *
     * 根据 id    删除文件夹名称
     *
     */
    public function deleteItem($id){

        return $this->wpdb->query("update  `wp_catalogs` set isValid='1'  where id='".$id."' ");
    }






    public function add_uploaded_file($id,$name,$filename,$pdfname){
        $result1=  $this->wpdb->get_results("SELECT listOrder FROM wp_catalogs order by listOrder desc limit 0,1 " );
        $num=$result1[0]->listOrder+1;
        $query="INSERT INTO `wp_catalogs` ( `type`, `parentId`, `name`, `fileAddr`, `pdfAddr`, `createTime`, `isValid`, `listOrder`,`display` ) VALUES ( '1', '".$id."', '".$name."', '".$filename."', '".$pdfname."',now(), '0', '".$num."', '0')";
        return  $this->wpdb->query($query);
    }


    /*
     *
     * 根据 id he  filename 修改天气路线
     *
     */
    public function changeDisplay($id,$display){

        return $this->wpdb->query("update  `wp_catalogs` set display='".$display."' where id='".$id."' ");
    }

    /*
     *
     * 修改某一条目位置
     */
    public function changeOrder($id,$upOrDown){

        $querystr = "SELECT * FROM wp_catalogs WHERE id ='".$id."'  and isValid='0'  "  ;
        $reslut = $this->wpdb->get_results($querystr);
        if(count($reslut)>0) {
            if ($upOrDown == 1) ///上移
                $querystr = "SELECT  * FROM wp_catalogs WHERE parentId ='" . $reslut[0]->parentId . "'  and isValid='0'and listOrder<'" . $reslut[0]->listOrder . "'  ORDER BY listOrder desc limit 0,1 ";
            else
                $querystr = "SELECT   * FROM wp_catalogs WHERE parentId ='" . $reslut[0]->parentId . "'  and isValid='0'and listOrder>'" . $reslut[0]->listOrder . "'  ORDER BY listOrder limit 0,1 ";
            //return $querystr;
            $changereslut = $this->wpdb->get_results($querystr);
            if(count($changereslut)>0) {
                $this->wpdb->query("update  `wp_catalogs` set listOrder='".$changereslut[0]->listOrder."' where id='".$id."' ");
                $this->wpdb->query("update  `wp_catalogs` set listOrder='".$reslut[0]->listOrder."' where id='".$changereslut[0]->id."' ");
                return 1;
            }
        }


        return 0;
    }



    /*
        *
        * 根据 id he  filename 修改天气路线
        *
        */
    public function changeDirType($id){

        return $this->wpdb->query("update  `wp_catalogs` set type=6-type where id='".$id."' ");
    }



    public function makeFile($filename){
        if ($handle = fopen($filename, 'w')) {
            fclose($handle);
            return true;
        }
        return false;
    }

    public function filemtime ($filename) {
        return @filemtime($filename);
    }

    public function copyFile ($from, $to) {
        return @copy($from, $to);
    }

    public function copyDir ($src, $dst) {
        $dir = opendir($src);
        $result = @mkdir($dst);
        while(false !== ( $file = readdir($dir)) ) {
            if (( $file != '.' ) && ( $file != '..' )) {
                if ( is_dir($src . '/' . $file) ) {
                    $this->copyDir($src . '/' . $file, $dst . '/' . $file);
                }
                else {
                    copy($src . '/' . $file,$dst . '/' . $file);
                }
            }
        }
        closedir($dir);
        return $result;
    }

    public function renameItem ($from, $to) {
        return @rename($from, $to);
    }

    public function readFile($filename){
        return file_get_contents($filename);
    }

    public function writefile($filename, $content){
        return @file_put_contents($filename, $content);
    }

    public function move_uploaded_file ($from, $to) {
        return @move_uploaded_file($from, $to);
    }

    public function parseImage($ext,$img,$file = null){
        $result = false;
        switch($ext){
            case 'png':
                $result = imagepng($img,($file != null ? $file : ''));
                break;
            case 'jpeg':
                $result = imagejpeg($img,($file ? $file : ''),90);
                break;
            case 'jpg':
                $result = imagejpeg($img,($file ? $file : ''),90);
                break;
            case 'gif':
                $result = imagegif($img,($file ? $file : ''));
                break;
        }
        return $result;
    }

    public function imagecreatefrompng($src) {
        return imagecreatefrompng($src);
    }

    public function imagecreatefromjpeg($src){
        return imagecreatefromjpeg($src);
    }

    public function imagecreatefromgif($src){
        return imagecreatefromgif($src);
    }
}

class GSFileManager {

    private $options;
    private $opt_param = 'opt';
    public static $root_param = 'rootDir';
    private $fileStorage;
    private $setUtf8Header = true;
    private $functions;
    private $itemNameRegex = '[/\?\*;:{}\\\\]+';

    private $destfile="";
    private $destpdf="";

    public function __construct($fileStorage, $options){
        $this->fileStorage = $fileStorage;
        $this->options = $options;
        $this->functions = array();
        $this->functions[1] = 'listDir';
        $this->functions[2] = 'makeFile';
        $this->functions[3] = 'makeDirectory';
        $this->functions[4] = 'deleteItem';
        $this->functions[5] = 'copyItem';
        $this->functions[6] = 'renameItem';
        $this->functions[7] = 'moveItems';
        $this->functions[8] = 'downloadItem';
        $this->functions[9] = 'readfile';
        $this->functions[10] = 'writefile';
        $this->functions[11] = 'uploadfile';
        $this->functions[12] = 'jCropImage';
        $this->functions[13] = 'imageResize';
        $this->functions[14] = 'copyAsFile';
        $this->functions[15] = 'serveImage';
        $this->functions[16] = 'zipItem';
        $this->functions[17] = 'unZipItem';




        $this->destfile=dirname(__FILE__) . '/../upfiles/';
        $this->destpdf=dirname(__FILE__) . '/../upfiles/pdf/';
    }


    /*
 *
 *根据不同的type 进行不同的操作
 *
 *
 */


    public function process($args){

        $actiontype=$args['opt'];

        /*
         *
         *$actiontype   ：
         *     1    显示目录
         *     2    新建文件夹
         *
         *     101 新建网址链接
         *     102  新建/更新 天气路线
         *
         *
         */


        ///读取目录
        if ($actiontype=='1') {
            $id = 1;
            if(isset($args['id']))
                $id=$args['id'];
            return $this->listDir($id);
        }

        ///读取pdf 网址  天气
        if ($actiontype=='2') {
            $id=$args['id'];
            return $this->readnode($id);
        }


        /////

        $responce = '';
        $functionName = $this->getRequestFunction($args[$this->opt_param]);

        if ($functionName != null) {
            $responce = $this->$functionName($args);
        } else {
            throw new Exception('ILlegalArgumentException: Uknown action '.$args[$this->opt_param], 6);

        }
        if ($this->setUtf8Header) {
            header ("Content-Type: text/html; charset=utf-8");
        }
        return $responce;
    }


    /*
    *
    * ////根据id 查询数据库该条目
    *
    *
    */
    public function readnode($id) {

        $resultjson=json_encode(array('status' => 0,'type'=>1, 'data' =>'' ));
        $result=$this->fileStorage->file_exists_1($id);
        if(count($result)>0 ) {

            if($result[0]->type == '1')  /////文件
                $resultjson=json_encode(array('status' => 1, 'data' => "<iframe class=\"pdf-container\" src=\"upfiles/pdf/".$result[0]->pdfAddr."\"></iframe>" ));
            else if($result[0]->type == '0')  ///网址
                $resultjson=json_encode(array('status' => 1, 'data' => $result[0]->netAddr));
            else if($result[0]->type == '3')  //// 天气
            {

                $data = array();
                array_push($data,array('title' => "ZBAA北京首都",'content'=>"METAR ZBAA 231700Z VRB01MPS CAVOK M05/M13 Q1034 NOSIG=<br/>TAF ZBAA 231630Z 231803 32004MPS CAVOK TX00/03Z TNM07/21Z=<br/>TAF ZBAA 231530Z 231818 32004MPS CAVOK TX03/06Z TNM07/21Z TEMPO 0612 19005MPS=<br/>",'link'=>"#" ));
                array_push($data,array('title' => "ZSSS上海虹桥",'content'=>"METAR ZSSS 231700Z 31006MPS 6000 BKN015 03/00 Q1032 NOSIG=<br/>TAF ZSSS 231604Z 231803 33006MPS 5000 BR BKN015 TX07/03Z TN02/21Z=<br/>TAF ZSSS 231512Z 231818 34006MPS 5000 BR BKN015 TX09/06Z TN02/21Z=<br/>",'link'=>"#" ));
                array_push($data,array('title' => "ZPPP昆明长水",'content'=>"METAR ZPPP 231700Z VRB01MPS CAVOK 08/05 Q1025 NOSIG=<br/>TAF ZPPP 231611Z 231803 04004MPS CAVOK TX12/03Z TN03/22Z BECMG 2223 22005MPS=<br/>TAF ZPPP 231314Z 231818 04004MPS CAVOK TX19/08Z TN03/23Z BECMG 2223 22005MPS=<br/>",'link'=>"#" ));
                array_push($data,array('title' => "ZSNJ南京禄口",'content'=>"METAR ZSNJ 231700Z 32004MPS 8000 OVC023 M00/M02 Q1035 NOSIG=<br/>TAF ZSNJ 231601Z 231803 33004MPS 3000 BR NSC TX03/03Z TNM02/21Z=<br/>TAF ZSNJ 231526Z 231818 33004MPS 3000 BR NSC TX06/06Z TNM02/21Z=<br/>",'link'=>"#" ));
                array_push($data,array('title' => "ZSQD青岛",'content'=>"METAR ZSQD 231700Z 33003MPS CAVOK M03/M10 Q1033 NOSIG=<br/>TAF ZSQD 231618Z 231803 32004MPS 5000 BR NSC TX04/03Z TNM06/21Z=<br/>TAF ZSQD 231516Z 231818 32004MPS 5000 BR NSC TX06/06Z TNM06/21Z=<br/>",'link'=>"#" ));
                array_push($data,array('title' => "WS报文",'content'=>"ZHWH SIGMET 7 VALID 231410/231810 ZHHH- ZHWH WUHAN FIR SEV TURB FCST N OF N28 FL260/360 STNR NC=<br/>ZJSA SIGMET 3 VALID 231430/231830 ZJHK- ZJSA SANYA FIR EMBD TS FCST N OF N1748 AND S OF N1930 AND E OF E10848 TOP FL350 MOV SE 25KMH NC=<br/>VHHK SIGMET 6 VALID 231520/231920 VHHH- VHHK HONG KONG FIR EMBD TS FCST N OF N1812 AND S OF N2000 AND W OF E11406 TOP FL400 STNR NC=<br/>",'link'=>"#" ));
                $resultjson = json_encode(array('status' => 1,'type'=>1, 'data' =>$data));

            }
            else if($result[0]->type == '4')  //// 迭代文件夹
            {

                $fileresult=$this->fileStorage->lastfile($id);
                if(count($fileresult)>0 ) {
                    $resultjson=json_encode(array('status' => 1, 'data' => "<iframe class=\"pdf-container\" src=\"upfiles/pdf/".$fileresult[0]->pdfAddr."\"></iframe>" ));
                }


            }
            return $resultjson;
        }

        return $resultjson;
    }


    /*
    *
    *   ////根据id
    *
    */
    public function listDir($id) {

        $result=$this->fileStorage->file_exists_1($id);
        if(count($result)>0 ) {
            $files = $this->fileStorage->scandir($id);
            $data = array();
            if( count($files) > 0 ) {
                foreach( $files as $file ) {

                    /*
                     * type 类型  2 文件夹   1  文件 0 网址
                     */
                    if( $file->type == '2') {
                        ///是文件
                        ///// 自身文件名  绝对路径 是否显示  id  文件类型名  时间
                        array_push($data,array('id' => intval($file->id),'label'=>$file->name,'isLeaf'=>false,'type'=>intval($file->type) ));
                    } else{  ///是文件
                        array_push($data,array('id' =>intval( $file->id),'label'=>$file->name,'isLeaf'=>true,'type'=>intval($file->type )));

                    }

                }

            }
            $result=json_encode(array('status' => 1, 'data' => $data));
            return $result;
        } else {
            $result=json_encode(array('status' => 0, 'data' =>'' ));
        }
    }



    public function downloadItem($args) {

        if (isset($args['filename'])) {
            $filename = $args['filename'];
            $dir = $args['dir'];
            $dest = dirname(__FILE__) . '/../upfiles/';
            $result = $this->fileStorage->file_exists_1($dir);
            //for windwow
            //$localfilename= iconv("UTF-8", "GB2312",$filename);
            // for linux
            $localfilename= iconv("UTF-8", "GBK",$result[0]->fileAddr);
            if ($this->fileStorage->file_exists($dest.$localfilename)) {
                $content = $this->fileStorage->readFile($dest . $localfilename);
                header('Content-Description: Download File: ' . $filename);

                header('Content-Description: Download File: ' . $filename);
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename="' . $filename . '"');
                header('Content-Transfer-Encoding: binary');
                header('Expires: 0');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                header('Pragma: public');
                header('Content-Length: ' . strlen($content));
                echo $content;
                exit;
            } else {
                throw new Exception('ILlegalArgumentException: Source does NOT exists', 7);
            }
        }
        else {
            throw new Exception('ILlegalArgumentException: filename can NOT be null', 5);
        }
    }



}




set_time_limit(0);
error_reporting(E_ALL);
ini_set('display_errors', true);
mb_internal_encoding("UTF-8");

$options = array();
$options['max_upload_filesize'] = '-1'; //(the size in Kbytes)
$manager = new GSFileManager(new GSFileSystemFileStorage($wpdb), $options);
try {

    $result =$manager->process($_REQUEST);

} catch (Exception $e) {
    $result = '{result: \'0\', gserror: \''.addslashes($e->getMessage()).'\', code: \''.$e->getCode().'\'}';
}
echo $result;








?>